/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.tasks
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.utils.getTimer;

	/**
	 * Task container that runs its own timer and updates all subtasks.
	 */
	public class TaskRunner extends TaskContainer
	{
		protected var source:IEventDispatcher;
		private var lastUpdate:uint;
		
		/**
		 * Create a TaskRunner instance.
		 *
		 * @param enterFrameSource The EventDispatcher from where the ENTER_FRAME events will be listened.
		 */
		public function TaskRunner(enterFrameSource:IEventDispatcher)
		{
			this.source = enterFrameSource;
			super();
		}

		/**
		 * @inheritDoc
		 */
		public override function start():void
		{
			if (running) return;
			this.lastUpdate = getTimer();
			source.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
			super.start();
		}
		
		/**
		 * @inheritDoc
		 */
		public override function stop():void
		{
			if (!running) return;
			source.removeEventListener(Event.ENTER_FRAME, this.onEnterFrame);
			super.stop();
		}

		protected function onEnterFrame(ev:Event):void
		{
			var step:int = getTimer() - this.lastUpdate;
			this.lastUpdate = getTimer();
			
			// Computer date might have changed; ignore this tick.
			if (step <= 0 || step > 10000)
				return;

			this.update(step);
		}
	}
}
